package cn.juque.lucenecandy.core.datasync.listener.impl;

import cn.hutool.core.collection.CollUtil;
import cn.juque.lucenecandy.bo.IndexUpdateParamBO;
import cn.juque.lucenecandy.core.base.BaseEntity;
import cn.juque.lucenecandy.core.constants.StrConstant;
import cn.juque.lucenecandy.core.datasync.listener.ICommitListener;
import cn.juque.lucenecandy.core.enums.DocSyncTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>NotSyncCommitListener</li>
 * </ul>
 * @date 2024-01-09
 **/
@Slf4j
@Service("notSyncCommitListener")
@Order(-999)
public class NotSyncCommitListener implements ICommitListener {

    /**
     * 事前操作
     *
     * @param param 参数
     * @return boolean，false将会取消提交
     */
    @Override
    public Boolean before(IndexUpdateParamBO param) {
        if (DocSyncTypeEnum.DEFAULT.equals(param.getSyncType()) || Boolean.TRUE.equals(param.getIgnoreSync())) {
            return false;
        }
        // 删除操作
        if (DocSyncTypeEnum.DEL.equals(param.getSyncType())) {
            return CollUtil.isNotEmpty(param.getIdList());
        }
        if (CollUtil.isEmpty(param.getContent())) {
            log.warn("数据同步发现空报文, index={}", param.getIndexName());
            return false;
        }
        List<? extends BaseEntity> list = param.getContent().stream().filter(f -> {
            Set<String> set = CollUtil.isEmpty(f.getAttachInfo()) ? new HashSet<>(0) : f.getAttachInfo();
            return !set.contains(StrConstant.NOT_SYNC);
        }).collect(Collectors.toList());
        if (CollUtil.isEmpty(list)) {
            log.warn("过滤不需同步数据后，数据同步发现空报文, index={}", param.getIndexName());
            return false;
        }
        param.setContent(list);
        return true;
    }

    /**
     * 事后操作
     *
     * @param param 参数
     */
    @Override
    public void after(IndexUpdateParamBO param) {
        // do nothing
    }
}
